/**
 * Created by Dalyn on 2017/2/28.
 */
import React from "react";
import Select from '../../../common/Select'
import InputBox from '../../../common/InputBox'
import PackTradeApply from './PackTradeApply'
import Relay from "react-relay";
import Createorder_StepOne from "./Createorder_StepOne";
import Createorder_DetailItem_Yarn from "./Createorder_DetailItem_Yarn";
import ReactKey from "../../../util/ReactKey"
import AddExistStyleModal from "./AddExistStyleModal"
import Creatorder_StepThree from "./Createorder_StepThree";
import CalendarModal from "./CalendarModal";
import DetailUploadModal from "./DetailUploadModal";
import AddImgModal from "./AddImgModal";
import {Modal,Carousel,message} from 'antd';
import AddPartBModal from "./AddPartBModal";
import SaveOrderMutation from "./mutation/SaveOrderMutation"
import TotalCount from "./TotalCount"
import TotalCountChinese from "./TotalCountChinese"
import getEnOrderTypeMutation from "./mutation/GetEnOrderTypeMutation"
import ReactDOM from 'react-dom';
import { hashHistory } from 'react-router';
import DelQiniuFileMutation from "./mutation/DelQiniuFileMutation"
import Util from "../../../util/Util"
import ToLeadExcelModal from "./ToLeadExcelModal"
import './css/create_order_common.css'
import Config from "../../../util/Config"
/*信息列表*/
export default class Createorder extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num: 0,
            goods: [],
            goodsremark: [],
            showitembottom: false,
            instructions: [],
            orderId:"",
            ordertype_num:"",
        };

        this.goods = [{}, {}, {}];
        this.goodsremark = [{}, {}, {}];
        this.showitembottom = false;
        this.ordertype_num = "5";
        this.instructions = [];
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.additemlist = this.additemlist.bind(this);
        this.delteitem = this.delteitem.bind(this);
        this.addremarkitemlist = this.addremarkitemlist.bind(this);
        this.deremarkteitem = this.deremarkteitem.bind(this);
    }


    componentWillMount() {
        this.state.num = this.goods.length;
        this.setState({
            goods: this.goods,
            goodsremark: this.goodsremark
        });
        /*获取当前企业可发布订单类型*/
        /*Relay.Store.commitUpdate(
         new getEnOrderTypeMutation({
         enId :this.enterpriseId,
         }),
         {
         onFailure: () => {
         console.log("请求失败-乙方企业")
         },
         onSuccess: (response) => {
         let errorCode = response.getEnOrderType.getEnOrderType.errorCode;
         let ordertype = [];
         if(errorCode=="0"){
         ordertype = response.getEnOrderType.getEnOrderType.enOrderType.ordertype;
         ordertype = JSON.parse(ordertype);
         ordertype.map((item,index)=>{
         this.ordertype.push(item)
         });
         this.setState({
         ordertype:this.ordertype
         });
         // console.log(this.ordertype);
         }
         }
         }
         )*/

    }

    /*选择订单类型*/
    /* chooseordertype(id){
     console.log(id);
     this.ordertype_num = id;
     }*/

    handleclick() {
    }

    showimgmodal(index){
        this.refs.addimg.setState({
            visible:true,
            index:index
        });
    }

    setgoodsimg(url,index){
        if(!url){
            Modal.warning({
                title: '图片',
                content: '请选择图片',
            });
            return;
        }
        if(index+1){
            let goods = this.state.goods
            goods[index].url = url;
            this.setState({
                goods:goods
            });
        }else{
        }
        this.refs.addimg.setState({
            visible:false
        });
    }

    additem() {
        return this.state.goods.map((context, index)=> {
            let isshow = true
            return (
                <Createorder_DetailItem_Yarn context={context} index={index} key={ReactKey.key}
                                        additemlist={this.additemlist}
                                        delteitem={this.delteitem}
                                        totallenght={this.state.goods.length}
                                        repalceitem={this.repalceitem.bind(this)}
                                        isshow={isshow}
                                        showimgmodal = {this.showimgmodal.bind(this)}
                                        ref={'creatorderditem'+index}
                                        setcountcallback = {this.setcountcallback.bind(this)}
                />
            );
        });
    }

    repalceitem(context, index) {
        let goods = this.state.goods;
        goods.splice(index, 1, context);
        this.setState({
            goods: goods
        });
    }

    showitemall() {
        this.setState({
            showitembottom: true
        });
    }

    additembottom() {
        if (this.state.showitembottom || this.state.goods.length < 5) {
            return (
                null
            );

        } else {
            return (
                <div onClick={this.showitemall.bind(this)}>
                    是否显示全部
                </div>
            );
        }

    }

    /*根据订单类型展示dom*/
    /*addpurchasetype() {
     if (this.entype == "6") {//贸易商
     return (
     <p style={{width: 1114, height: 58, paddingLeft: "60px", lineHeight: "58px", background: "#f4fafa", border: "1px solid #cacaca",position:"relative",marginBottom:"20px",position:"relative"}}>
     <span
     style={{position:"absolute",left:"50px",top:"20px",color:"red",display:"block",fontSize:"16px"}}>*</span>
     采购商品：
     <span
     style={{display:"block",marginLeft:"20px",marginTop:"20px",width:119,height:25,display:"block",border:"1px lolid #36b3b3",borderColor:"#36b3b3",position:"absolute",left:"100px",top:"0px"}}>
     成衣
     </span>
     </p>
     );

     } else {
     // console.log(this.state.ordertype);
     return (
     <p style={{width: 1114, height: 58, paddingLeft: "60px", lineHeight: "58px", background: "#f4fafa", border: "1px solid #cacaca",position:"relative",marginBottom:"20px"}}>
     <span
     style={{position:"absolute",left:"50px",top:"25px",color:"red",display:"block",fontSize:"16px"}}>*</span>
     采购商品：
     <Select oArr={this.ordertype} onselectchose={this.chooseordertype.bind(this)} ref={"_ordertype"}
     style={{marginLeft:"20px",marginTop:"20px",width:119,height:25,display:"block",border:"1px lolid #36b3b3",borderColor:"#36b3b3"}}/>
     </p>
     );
     }
     }*/

    /*第一步*/
    addstepone() {
        return (
            <Createorder_StepOne ispartA={this.ispartA} enterpriseId={this.enterpriseId} ref={'stepone'}/>
        );
    }

    addStepThree() {
        return this.state.goodsremark.map((context, index)=> {
            return (
                <Creatorder_StepThree key={ReactKey.key} index={index} context={context}
                                      addremarkitemlist={this.addremarkitemlist}
                                      deremarkteitem={this.deremarkteitem}
                                      totallenght={this.state.goodsremark.length}
                />
            );
        });
    }

    delqiniufile(item, fileKye) {
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: fileKye
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        Util.removedarrayitem(this.instructions, item);
                        this.setState({
                            instructions: this.instructions
                        });
                    }
                }
            }
        )
    }

    addinstructions() {
        if (this.instructions.length >= 5) {
            alert('不能超过5个');
            return
        }
        this.refs.deup.setState({
            visible: true
        });
    }

    addpact(name, hash, url, fileKey,sid) {
        this.instructions.push({"name": name, "hash": hash, "url": url, "fileKey": fileKey,"sid":sid});
        this.setState({
            instructions: this.instructions
        });
    }

    attach() {
        if (this.instructions) {

        }
        return this.state.instructions.map((item, index)=> {
            return (
                <PackTradeApply key={ReactKey.key} item={item} delqiniufile={this.delqiniufile.bind(this)} type={'accessory'}/>
            );

        })
    }

    showlibrary() {

        this.refs.addesm.setState({
            visible: true
        });
    }

    addModalfromlist(orders) {
        if(orders.length==0){}else{
            let goods = this.state.goods;
            let goodstest = [];
            let addindex = [];
            goods.map((context,index)=>{
                let values = Object.values(context);
                if(values.length!=0){
                    addindex.push(index)
                }
            });
            addindex.map((context)=>{
                goodstest.push(goods[context])
            });

            let tgoods = goodstest.concat(orders);
            this.setState({
                goods: tgoods
            });
        }
        this.refs.addesm.setState({
            visible: false,
        });
    }

    additemlist() {
        let goods = this.state.goods;
        goods.push({});
        this.setState({
            goods: goods
        });

    }

    delteitem(index) {
        let goods = this.state.goods;
        goods.splice(index, 1);
        this.setState({
            goods: goods
        },()=>{
            this.setcountcallback();
        });
    }

    addremarkitemlist() {
        let goodsremark = this.state.goodsremark;
        goodsremark.push({});
        this.setState({
            goodsremark: goodsremark
        });

    }

    deremarkteitem(index) {
        let goodsremark = this.state.goodsremark;
        goodsremark.splice(index, 1);
        this.setState({
            goodsremark: goodsremark
        });
    }

    setcountcallback(){
        let total = 0;
        let totalmoney=0;
        this.state.goods.map((context,index)=>{
            let quantity = this.refs['creatorderditem'+index].state.context.quantity;
            let price = this.refs['creatorderditem'+index].state.context.price;
            if(quantity){
                total = total+Number(quantity);
                total = Math.ceil(total);
            }
            if(quantity&&price){
                let temptotal = Number(quantity)*Number(price)
                if(!isNaN(totalmoney)){
                    totalmoney = parseFloat(totalmoney)+temptotal
                    totalmoney = parseFloat(totalmoney).toFixed(2);
                }
            }
        });
        this.refs.totalcount.setState({
            quantity:total,
            totalprice:totalmoney
        });
        this.refs.totalcountchinese.setState({
            count:totalmoney,
        });
    }

    addfrom(){
        return(
            <div className="order_form_total_div">
                <span className="order_form_top_span">
                </span>
                <table className="order_form_table">
                    <thead>
                    <tr className="order_from_tr">
                        <td className="order_frorm_td order_from_td_num order_detail_thead_style"/>
                        <td className="order_frorm_td order_from_td_snum order_detail_thead_style">款号</td>
                        <td className="order_frorm_td order_from_td_cnum order_detail_thead_style">品名</td>
                        <td className="order_frorm_td order_from_td_describe order_detail_thead_style">描述</td>
                        <td className="order_frorm_td order_from_td_size order_detail_thead_style">规格</td>
                        <td className="order_frorm_td order_from_td_monad order_detail_thead_style">单位</td>
                        <td className="order_frorm_td order_from_td_ucost order_detail_thead_style">单价</td>
                        <td className="order_frorm_td order_from_td_pnum order_detail_thead_style">数量</td>
                        <td className="order_frorm_td order_from_td_moeny order_detail_thead_style">金额</td>
                        <td className="order_frorm_td order_from_td_size order_detail_thead_style">纱线类型</td>
                        <td className="order_frorm_td order_from_td_size order_detail_thead_style">成纱状态</td>
                        <td className="order_frorm_td order_from_td_size order_detail_thead_style">成分</td>
                        <td className="order_frorm_td order_from_td_size order_detail_thead_style">纱支</td>
                        <td className="order_frorm_td order_from_td_size order_detail_thead_style">备注</td>
                        <td className="order_frorm_td order_from_td_delandadd order_detail_thead_style"/>
                    </tr>
                    </thead>
                    {
                        this.additem()
                    }

                    <TotalCount ref={'totalcount'} type={'yarn'}/>

                    <TotalCountChinese ref={"totalcountchinese"} type={'yarn'}/>

                </table>

            </div>
        );
    }
    /*点击创建*/
    creatorder(){
        let goods = [];
        let goodremark = [];
        let instructions =[];
        this.state.goods.map((context,index)=>{
            if(context.price&&context.quantity){
                goods.push(context)
            }
        });
        this.state.goodsremark.map((context,index)=>{
            if(context.deliverDate&&context.amount){
                goodremark.push(context)
            }
        });

        this.state.instructions.map((context)=>{
            if(context.sid){
                instructions.push(context.sid);
            }else{
                instructions.push('');
            }

        });

        if(goods.length==0){
            message.info('请完整填写订单数据');
            return;
        }

        goods[0].price = Number((Number(goods[0].price)).toFixed(2));

        let goodssty = JSON.stringify(goods);
        let stests = JSON.stringify(goodremark);
        let parentId = ReactDOM.findDOMNode(this.refs.stepone.refs.partAord).selectedOptions[0].innerHTML;
        let createUser = sessionStorage.getItem('uid');
        let account = this.refs.totalcount.state.totalprice*100;
        let partAName = sessionStorage.getItem('enterpriseName');
        let partA = sessionStorage.getItem('enterpriseId');
        let partAAddress = this.refs.stepone;
        let partAUserName = sessionStorage.getItem('username');
        let address = sessionStorage.getItem('address');
        let remark = this.refs.remarkinput.state.text;
        Relay.Store.commitUpdate(
            new SaveOrderMutation({
                parentId:parentId,
                createUser:createUser,
                enId:partA,
                account:account,
                payAccount:0,
                orderType:'5',
                partA:partA,
                partAName:partAName,
                partAAddress:address,
                partAUserId:createUser,
                partAUserName:partAUserName,
                rmark:remark,
                goodsInfo:goodssty,
                traderUrl1:'',
                traderUrl2:'',
                traderUrl3:'',
                traderUrl4:'',
                traderUrl5:'',
                contractUrl1:instructions[0]||'',
                contractUrl2:instructions[1]||'',
                contractUrl3:instructions[2]||'',
                contractUrl4:instructions[3]||'',
                contractUrl5:instructions[4]||'',
                deliverRequest:stests
            }),
            {
                onFailure: () => {
                    message.info('创建失败');
                },
                onSuccess: (response) => {
                    let errorCode = response.saveOrder.saveOrder.errorCode;
                    let order = response.saveOrder.saveOrder.order;
                    if(errorCode == 0){
                        hashHistory.push({pathname:'/publishOrder/',state:{'enterpriseId':this.enterpriseId,'entype':this.entype,'ordertype_num':this.ordertype_num,
                            'oid':order.oid,'orderType':order.orderType,'account':order.account}});
                    }
                }
            }
        )
    }

    deletorder(){

    }
    _DownLodaExcel(){
        window.location.href = Config.qiuniu+'%E7%BA%B1%E7%BA%BF%E5%95%86%E5%93%81%E6%98%8E%E7%BB%86%E6%A8%A1%E6%9D%BF%20.xlsx';
    }

    _ToLeadExcel(){
        this.refs.tolead.setState({
            visible:true
        });
    }

    toLeadExcel(orders){
        if(orders.length==0){

        }else{
            let goods = this.state.goods;
            let goodstest = [];
            let addindex = [];
            goods.map((context,index)=>{
                let values = Object.values(context);
                if(values.length!=0){
                    addindex.push(index)
                }
            });
            addindex.map((context)=>{
                goodstest.push(goods[context])
            });

            let tgoods = goodstest.concat(orders);
            this.setState({
                goods: tgoods
            },()=>{
                this.setcountcallback();
            });
        }
    }

    render() {
        return (
          <div className="orderdetail_box" style={{width: 1233, marginTop:10,minHeight: 875, background: "#f5f5f5",paddingBottom:"30px"}}>

                <div style={{width: 1174, minHeight: 500, background: "#fff", padding: "20px"}}>
                    {/*{
                     this.addpurchasetype()
                     }*/}

                    <div
                        style={{width:1174,minHeight:500,border:"1px dashed #ccc",borderRadius:"5px",position:"relative",paddingBottom:"30px"}}>
                        {
                            this.addstepone()
                        }
                        <p className="create_order_step">
                            第二步：添加商品明细
                            <span className="create_order_step_line"/>
                        </p>
                        <p className="create_order_download">
                          <a
                              style={{color: "#36b3b3", fontSize: "12px",cursor:'pointer'}}
                              onClick={this._DownLodaExcel.bind(this)}>下载excel导入模板</a>
                          <a
                            style={{color: "#36b3b3", fontSize: "12px",cursor:'pointer'}}
                            onClick={this._ToLeadExcel.bind(this)}>excel导入商品</a>
                          {
                            //<span className="create_order_excel_in" onClick={this.showlibrary.bind(this)}>+从商品库选择</span>
                          }
                        </p>

                        {
                            this.addfrom()
                        }
                        <p className="create_order_step">
                            第三步：添加交货要求
                            <span  className="create_order_step_line"/>
                        </p>

                        <table className="order_form_table" style={{marginLeft:'20px'}}>
                            <thead>
                            <tr className="order_from_tr">
                                <td className="order_frorm_td order_frorm_td_three_time order_detail_thead_style">交货时间</td>
                                <td className="order_frorm_td order_frorm_td_three_num order_detail_thead_style">数量</td>
                                <td className="order_frorm_td order_frorm_td_three_remark order_detail_thead_style">备注</td>
                                <td className="order_frorm_td order_frorm_td_three_adddetel order_detail_thead_style"/>
                            </tr>
                            </thead>
                            {
                                this.addStepThree()
                            }
                        </table>
                        <p className="create_order_step">
                            第四步：添加备注
                            <span className="create_order_step_line"/>
                        </p>



                        <div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                          <span style={{position: "absolute", top: "0px", left: "81px"}}>备注：</span>
                            <InputBox multiline space={"20"}
                                      style={{width: 980, height: 174,paddingRight:"60px",borderColor:"#36b3b3"}} ref={'remarkinput'}/>
                        </div>
                        <div style={{minHeight: 0, marginLeft: "40px", marginTop: "20px",overflow:"hidden"}}>
                            <div style={{float: "left"}}>
                                {
                                    this.attach()
                                }
                            </div>
                        </div>
                        <span className='create_add_contracts' onClick={this.addinstructions.bind(this)}>添加附件</span>

                        <button className="order_main_creat_button_new" onClick={this.creatorder.bind(this,this.imageUrl,this.state.index)}>
                            创建</button>


                        <div className="order_main_creat_div"></div>
                    </div>
                </div>

                <AddExistStyleModal ref={'addesm'} ordertype_num={this.ordertype_num} addModalfromlist={this.addModalfromlist.bind(this)} key={ReactKey.key}/>
              <ToLeadExcelModal ref = {'tolead'} mid={'tolead'} toLeadExcel={this.toLeadExcel.bind(this)} type = '5'/>
                <DetailUploadModal ref={'deup'} addpact={this.addpact.bind(this)} mid={'creat'}/>
                <CalendarModal ref={'calendar'}/>
                <AddImgModal ref={'addimg'} setgoodsimg={this.setgoodsimg.bind(this)} key={ReactKey.key}/>
                <AddPartBModal ref={'addpartb'} key={ReactKey.key} enterpriseId={this.enterpriseId} entype={this.entype} ordertype_num={this.ordertype_num}/>
            </div>
        )
    }
}
